package controllers

import (
	"2105A/web/models"
	"2105A/web/utils"
	"context"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/beego/beego/v2/core/logs"

	"github.com/beego/beego/v2/adapter/validation"

	beego "github.com/beego/beego/v2/server/web"
)

type UserController struct {
	beego.Controller
}

func (u *UserController) GetUserList() {
	username := u.GetString("username")
	user := models.GetUserList(username)
	fmt.Println(111)
	u.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"data": user,
		"msg":  "find successfully",
	}
	u.ServeJSON()
}

// 登录的方法 // API
func (u *UserController) Login() {

	// 输入用户名、密码
	username := u.GetString("username")
	password := u.GetString("password")

	// 对前端传递的数据进行验证
	valid := validation.Validation{}
	valid.Required(username, "username").Message("用户名不能为空")
	valid.Required(password, "password").Message("密码不能为空")
	valid.MinSize(password, 4, "password").Message("密码长度至少是4位")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			u.Data["json"] = map[string]interface{}{
				"code": http.StatusNonAuthoritativeInfo,
				"msg":  err.Message,
			}
			u.ServeJSON()
		}
	}

	// 密码错误的、需要存储当前用户名对应错误次数+1
	var login_pwd_err_times string = "login_pwd_err_times_" + username
	times, _ := utils.RedisClient.Get(context.Background(), login_pwd_err_times).Result()
	if t, _ := strconv.Atoi(times); t > 3 {
		u.Data["json"] = map[string]interface{}{
			"code": http.StatusNoContent,
			"msg":  "password error times more,please try again",
		}
		u.ServeJSON()
	}

	user, err := models.Login(username) // 调用模型包中的login方法
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": http.StatusNoContent,
			"msg":  "user not found",
		}
		u.ServeJSON()
	}

	// 验证密码
	if user.Password != utils.EncryptPassword(password) {
		logs.Error("password is incorrect")
		res, _ := utils.RedisClient.Exists(context.Background(), login_pwd_err_times).Result()
		if res == 0 {
			utils.RedisClient.Set(context.Background(), login_pwd_err_times, 1, time.Hour*24)
		} else {
			utils.RedisClient.Incr(context.Background(), login_pwd_err_times)
		}

		u.Data["json"] = map[string]interface{}{
			"code": http.StatusNoContent,
			"msg":  "password is error",
		}
		u.ServeJSON()
	}

	// 登录成功以后 通过session、记录用户信息
	err = u.SetSession("username", username)
	if err != nil {
		logs.Info("存储session失败")
		fmt.Println(err)
	}
	logs.Info(username + "登录成功" + time.Now().String())
	////响应数据为json格式
	u.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"msg":  "success",
	}
	u.ServeJSON()
}

// 注册方法
func (u *UserController) Register() {
	// 输入用户名、密码
	username := u.GetString("username")
	password := u.GetString("password")
	mobile := u.GetString("mobile")
	err := models.Register(username, password, mobile)
	if err != nil {
		fmt.Println(err)
		u.Data["json"] = map[string]interface{}{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		}
		u.ServeJSON()
	}
	fmt.Println("post register method")
	u.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"msg":  "register successfully",
	}
	u.ServeJSON()
}

func (u *UserController) Logout() {
	u.DelSession("username")
	u.Data["json"] = map[string]interface{}{
		"code": http.StatusOK,
		"msg":  "logout successfully",
	}
	u.ServeJSON()
}
